//
//  NSData+XCategories.m
//  FFoundation
//
//  Created by 三井 on 2019/12/31.
//

#import "NSData+XCategories.h"

@implementation NSData (XCategories)

- (NSData *)AES:(NSString *)key {
    NSMutableData *keyData = [[key dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
    
    size_t dataMoved;
    
    int size = kCCBlockSizeAES128;
    
    NSMutableData *decryptedData = [NSMutableData dataWithLength:self.length + size];
    
    int option = kCCOptionPKCS7Padding | kCCOptionECBMode;
    
    NSUInteger keyLength = keyData.length;
    if (keyLength <= 16) {
        [keyData setLength:16];
    } else if (keyLength > 16 && keyLength <= 24) {
        [keyData setLength:24];
    } else {
        [keyData setLength:32];
    }
    
    CCCryptorStatus result = CCCrypt(kCCEncrypt,                    // kCCEncrypt or kCCDecrypt
                                     kCCAlgorithmAES128,
                                     option,                        // Padding option for CBC Mode
                                     keyData.bytes,
                                     keyData.length,
                                     nil,
                                     self.bytes,
                                     self.length,
                                     decryptedData.mutableBytes,    // encrypted data out
                                     decryptedData.length,
                                     &dataMoved);                   // total data moved
    
    if (result == kCCSuccess) {
        decryptedData.length = dataMoved;
        return decryptedData;
    }
    return nil;
}

@end
